package org.ak47.spring.boot.grpc.autoconfigure;


import io.grpc.ClientInterceptor;
import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * <p> 全局客户端拦截器注册表 </p>
 *
 * @author hexiaohong
 */
@Getter
public class GlobalClientInterceptorRegistry implements ApplicationContextAware
{
    /**
     * 注册表
     */
    private final List<ClientInterceptor> clientInterceptors = new ArrayList<>();

    private ApplicationContext applicationContext;

    @PostConstruct
    public void init()
    {
        Map<String, GlobalClientInterceptorConfigurerAdapter> map = applicationContext.getBeansOfType(
            GlobalClientInterceptorConfigurerAdapter.class);
        for (GlobalClientInterceptorConfigurerAdapter adapter : map.values())
        {
            adapter.addClientInterceptors(this);
        }
    }

    public GlobalClientInterceptorRegistry addClientInterceptors(ClientInterceptor interceptor)
    {
        clientInterceptors.add(interceptor);
        return this;
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext)
        throws BeansException
    {
        this.applicationContext = applicationContext;
    }
}
